package org.lilred.nzbberry.ui;

import org.lilred.nzbberry.config.Resizer;
import org.lilred.nzbberry.util.FontFactory;
import org.lilred.nzbberry.util.ScaleImage;
import org.lilred.nzbberry.views.AppView;
import org.lilred.ui.ClickableField;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Graphics;

public class BannerButton extends ClickableField {
	Bitmap bitmap = new Bitmap(0, 0);
	Bitmap focusBitmap = new Bitmap(0, 0);
	String tooltip;
	int numBadges = 0;
	
	public BannerButton(String resource, String focusResource, String tooltip) {
		super(0);
		this.tooltip = tooltip;
		EncodedImage e = EncodedImage.getEncodedImageResource(resource);
		e = ScaleImage.toWidth(e, Resizer.resize(40));
		bitmap = e.getBitmap();
		e = EncodedImage.getEncodedImageResource(focusResource);
		e = ScaleImage.toWidth(e, Resizer.resize(40));
		focusBitmap = e.getBitmap();
	}
	protected void layout(int width, int height) {
		setExtent(bitmap.getWidth(), bitmap.getHeight());
	}
	
	public int getPreferredWidth() {
		return getWidth();
	}
	
	public int getPreferredHeight() {
		return getHeight();
	}

	protected void paint(Graphics g) {
		if (isFocus()) g.drawBitmap(0, 0, getWidth(), getHeight(), focusBitmap, 0, 0);
		else g.drawBitmap(0, 0, getWidth(), getHeight(), bitmap, 0, 0);
		if (numBadges > 0) {
			g.setFont(FontFactory.getFont(Resizer.resize(12)));
			String badgeText = Integer.toString(numBadges);
			int badgeHeight = g.getFont().getHeight() + 2 * 2;
			int badgeWidth = Math.max(g.getFont().getAdvance(badgeText) + 2 * Resizer.resize(3), badgeHeight);
			g.pushRegion(getWidth() - badgeWidth, getHeight() - badgeHeight, badgeWidth, badgeHeight, 0, 0);
			g.setGlobalAlpha(125);
			g.setColor(0xFFFFFF);
			g.fillRoundRect(0, 0, badgeWidth, badgeHeight, badgeHeight, badgeHeight);
			g.setColor(0xFF0000);
			g.fillRoundRect(1, 1, badgeWidth - 2, badgeHeight - 2, badgeHeight - 2, badgeHeight - 2);
			g.setGlobalAlpha(255);
			g.setColor(0xFFFFFF);
			g.drawText(Integer.toString(numBadges), badgeWidth / 2 - g.getFont().getAdvance(badgeText) / 2, 3);
			g.popContext();
		}
	}
	
	protected void onFocus(int direction) {
		super.onFocus(direction);
		AppView.getInstance().appManager.updateFooter(tooltip);
	}

	public void setBadges(int numBadges) {
		this.numBadges = numBadges;
		invalidate();
	}
}
